<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/19
 * Time: 9:21
 */

namespace common\business\mdm;


use common\business\DbHandler;
use common\business\EhrHelper;
use common\helpers\StringUtil;
use common\models\kingdee\OrgAdmin;
use common\models\kingdee\OrgPosition;
use common\models\mdm\MdmDept;
use common\models\mdm\MdmPosition;
use common\result\ActionResult;
use yii\db\Exception;
use yii\db\Query;

class MdmPositionService extends DbHandler
{
    /**
     * @var string
     */
    protected $_department_number;
    public function setDepartmentNumber($department_number){
        $this->_department_number = $department_number;
    }

    /**
     * @param callback|null $writeBackHandler
     * @return ActionResult
     */
    public function sync($writeBackHandler = null){
        $totalResult = new ActionResult();
        $apiHandler = new MdmHandler();
        $apiHandler->setCrud(new MdmPositionCrud());

        $db = OrgPosition::getDb();

        if (!StringUtil::isNullOrWhiteSpace($this->_department_number)){
            $org = OrgAdmin::findOne([
                'FNUMBER' => $this->_department_number
            ]);

            $orgIdParams = [
                'fid' => $org->FID
            ];
            $cmd = $db->createCommand('SELECT t.fid FROM T_ORG_ADMIN t START WITH t.fid = :fid CONNECT BY t.fparentid = PRIOR fid', $orgIdParams);
//        $cmd->bindParam('fid', $orgId);
            try {
                $orgIdArr = $cmd->queryColumn();
            } catch (Exception $e) {
                return null;
            }
        }

        $query = (new Query())->from('T_ORG_POSITION TOP')
            ->leftJoin('T_ORG_POSITION TOPP', 'TOPP.FID = TOP.FPARENTID')
            ->leftJoin('T_ORG_ADMIN TOA', 'TOA.FID = TOP.FADMINORGUNITID')
            ->select([
                'POSTNAME' => 'TOP.FNAME_L2',
                'POSTCODE' => 'TOP.FNUMBER',
                'parent_postcode' => 'TOPP.FNUMBER',
                'org_id' => 'TOP.FADMINORGUNITID',
                'org_number' => 'TOA.FNUMBER',
                'STARTDATE' => 'to_char(TOP.FEFFDT, \'yyyy-MM-dd\')',//
            ]);

        if (!StringUtil::isNullOrWhiteSpace($this->_department_number)){
            $query->andFilterWhere([
                'in' , 'TOP.FADMINORGUNITID', $orgIdArr
            ]);
        }

        $query->orderBy([
            'TOP.FID' => SORT_ASC,
        ]);

        $totalCount = $query->count('*', $db);

        $offset = 0;
        $pageSize = 100;
        $count = $pageSize;

        while ($count >= $pageSize) {
            $all = $query->offset($offset)->limit($pageSize)->all($db);
            $count = count($all);
            $offset += $pageSize;
            foreach ($all as $position){
                $ssMdmOrg = EhrHelper::findSsMdmOrgByNumber($position['org_number']);
                if($ssMdmOrg){
                    $position['SSORG'] = $ssMdmOrg->PK_MDM_ORG;
                }

                $mdmDept = MdmDept::findOne(['DEPARTMENTCODE' => $position['org_number']]);
                if ($mdmDept){
                    $position['PK_DEF1'] = $mdmDept->PK_DEPARTMENT;

                    $parentMdmDept = EhrHelper::findParentMdmDept($mdmDept);
                    if ($parentMdmDept){
                        $position['PK_DEF2'] = $parentMdmDept->PK_DEPARTMENT;
                    }
                }

                $newMdmPosition = new MdmPosition();
                $newMdmPosition->setAttributes($position);

                $mdmPositionInDb = MdmPosition::findOne([
                    'POSTCODE' => $newMdmPosition->POSTCODE,
                ]);

                if (!$mdmPositionInDb){
                    $totalResult->addSubResult($apiHandler->create($newMdmPosition));
                }
                else {
                    $totalResult->addSubResult($apiHandler->update($newMdmPosition, $mdmPositionInDb, ['POSTNAME', 'POSTCODE', 'SSORG', 'PK_DEF1']));
                }
                if ($writeBackHandler){
                    $paramArr = [
                        'totalCount' => $totalCount,
                        'finishCount' => $totalResult->total_count,
                        'message' => $totalResult->message,
                    ];
                    call_user_func_array($writeBackHandler, $paramArr);
                }
            }
        }
        return $totalResult;
    }
}